import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:xiaomi_shop/app/api/api.dart';
import 'package:xiaomi_shop/app/services/xhttp.dart';
import 'package:xiaomi_shop/models/shopModel.dart';

class ShopController extends GetxController {
  var page = 0;
  var shopList = [].obs;
  late EasyRefreshController refreshController;
  var selectConditionId = 0.obs;
  var sort = "";
  GlobalKey<ScaffoldState> globalKey = GlobalKey<ScaffoldState>();
  /*二级导航数据*/
  List subHeaderList = [
    {
      "id": 1,
      "title": "综合",
      "fileds": "all",
      "sort":
          -1, // 排序     升序：price_1     {price:1}        降序：price_-1   {price:-1}
    },
    {"id": 2, "title": "销量", "fileds": 'salecount', "sort": -1},
    {"id": 3, "title": "价格", "fileds": 'price', "sort": -1},
    {"id": 4, "title": "新品优先", "fileds": 'is_new', "sort": 0},
    {"id": 5, "title": "筛选"}
  ];

  @override
  void onInit() {
    super.onInit();
    refreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true,
    );
    getShopListData(Get.parameters);
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  onRefresh() {
    page = 0;
    shopList.clear();
    getShopListData(Get.parameters);
    refreshController.resetFooter();
  }

  onLoadMore() {
    page++;
    getShopListData(Get.parameters);
  }

  // 二级导航选择
  selectCondition(Map<String, dynamic> map) {
    if (map['id'] == 4) {
      selectConditionId.value = map['id'];
      var param = Get.parameters;
      param['is_new'] = '1';
      sort = "";
      onRefresh();
      return;
    }
    if (map['id'] == 5) {
      globalKey.currentState!.openEndDrawer();
      return;
    }
    if (selectConditionId.value != map['id']) {
      selectConditionId.value = map['id'];
      sort = '${map['fileds']}_${map['sort'] * -1}';
      Get.parameters.remove('is_new');
      onRefresh();
    }
  }

  // 商品列表
  void getShopListData(Map<String, dynamic> param) {
    param["page"] = page.toString();
    if (sort.isNotEmpty) {
      param["sort"] = sort;
    } else {
      param.remove('sort');
    }
    XHttp.getInstance().get(Api.shopList, param).then((value) {
      Result result = value as Result;
      List list = result.data["result"] as List;
      shopList.addAll(
          list.map((e) => ShopModel.fromJson(e as Map<String, dynamic>)));
      refreshController.finishLoad(
          list.length < 10 ? IndicatorResult.noMore : IndicatorResult.success);
      refreshController.finishRefresh();
    });
  }
}
